<template>
  <view class="order-detail">
    <!-- 订单状态 -->
    <view class="status-section">
      <view class="status-card">
        <text class="status-title">订单状态</text>
        <text class="status-text" :class="`status-${orderDetail.status}`">
          {{ getStatusText(orderDetail.status) }}
        </text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="info-section">
      <view class="info-card">
        <view class="info-item">
          <text class="label">订单号：</text>
          <text class="value">{{ orderDetail.orderNo }}</text>
        </view>
        <view class="info-item">
          <text class="label">下单时间：</text>
          <text class="value">{{ formatDate(orderDetail.createTime) }}</text>
        </view>
        <view class="info-item">
          <text class="label">支付时间：</text>
          <text class="value">{{ orderDetail.payTime ? formatDate(orderDetail.payTime) : '未支付' }}</text>
        </view>
        <view class="info-item">
          <text class="label">支付方式：</text>
          <text class="value">{{ getPayTypeText(orderDetail.payType) }}</text>
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="products-section">
      <view class="section-title">商品信息</view>
      <view class="products-card">
        <view 
          v-for="detail in orderDetail.orderDetail" 
          :key="detail.id" 
          class="product-item"
        >
          <image :src="detail.productImage" class="product-image" mode="aspectFill" />
          <view class="product-info">
            <text class="product-name">{{ detail.productName }}</text>
            <text class="product-price">¥{{ detail.price }}</text>
            <text class="product-quantity">x{{ detail.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 优惠信息 -->
    <view v-if="orderDetail.orderCoupon" class="coupon-section">
      <view class="section-title">优惠信息</view>
      <view class="coupon-card">
        <view class="coupon-info">
          <text class="coupon-name">{{ orderDetail.orderCoupon.couponName }}</text>
          <text class="coupon-desc">{{ orderDetail.orderCoupon.couponDesc }}</text>
        </view>
        <text class="discount-amount">-¥{{ orderDetail.discountAmount }}</text>
      </view>
    </view>

    <!-- 价格信息 -->
    <view class="price-section">
      <view class="section-title">价格信息</view>
      <view class="price-card">
        <view class="price-item">
          <text class="label">商品总额：</text>
          <text class="value">¥{{ orderDetail.totalAmount }}</text>
        </view>
        <view v-if="orderDetail.discountAmount > 0" class="price-item">
          <text class="label">优惠金额：</text>
          <text class="value discount">-¥{{ orderDetail.discountAmount }}</text>
        </view>
        <view class="price-item total">
          <text class="label">实付金额：</text>
          <text class="value">¥{{ orderDetail.actualAmount }}</text>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="actions-section">
      <button 
        v-if="orderDetail.status === 0" 
        class="action-btn primary" 
        @click="handlePay"
      >
        立即支付
      </button>
      <button 
        v-if="orderDetail.status === 0 || orderDetail.status === 3"
        class="action-btn secondary" 
        @click.stop="handleCancel"
      >
        取消订单
      </button>
      <button 
        v-if="[3, 4, 5].includes(orderDetail.status)"
        class="action-btn secondary" 
        @click="handleDelete"
      >
        删除订单
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getOrderDetail, deleteOrder, orderCancel } from '@/api/order';

// 订单详情数据
const orderDetail = ref<any>({
  id: '',
  orderNo: '',
  status: 0,
  totalAmount: 0,
  payAmount: 0,
  discountAmount: 0,
  createTime: '',
  payTime: '',
  payType: 0,
  orderDetail: [],
  orderCoupon: null
});

// 获取订单状态文本
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: '待支付',
    1: '支付中',
    2: '支付成功',
    3: '支付失败',
    4: '已取消',
    5: '已完成'
  };
  return statusMap[status] || '未知状态';
};

// 获取订单状态颜色
const getStatusColor = (status: number) => {
  const colorMap: { [key: number]: string } = {
    0: '#ff6b00',
    1: '#ff6b00',
    2: '#07c160',
    3: '#ff4d4f',
    4: '#999999',
    5: '#07c160'
  };
  return colorMap[status] || '#999999';
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN');
};

// 获取支付方式文本
const getPayTypeText = (payType: number) => {
  const payTypeMap: { [key: number]: string } = {
    1: '微信支付',
    2: '余额支付',
    3: '积分支付',
    4: '支付宝支付'
  };
  return payTypeMap[payType] || '未知支付方式';
};

// 获取订单详情
const getOrderDetailData = async () => {
  try {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const { id, orderNo } = currentPage.options as any;
    
    if (!id) {
      uni.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 调用获取订单详情API
    const response = await getOrderDetail(Number(id));
    if (response.data) {
      // console.log('订单详情', response.data);
      orderDetail.value = response.data;
    } else {
      // 如果API返回失败，使用模拟数据
      orderDetail.value = {
        id: id,
        orderNo: orderNo || 'ORD202501130001',
        status: 1,
        totalAmount: 299.00,
        payAmount: 279.00,
        discountAmount: 20.00,
        createTime: '2025-01-13 10:30:00',
        payTime: '2025-01-13 10:35:00',
        payType: 1,
        orderDetail: [
          {
            id: 1,
            productName: 'iPhone 15 Pro',
            productImage: '/static/images/iphone15.jpg',
            price: 299.00,
            quantity: 1
          }
        ],
        orderCoupon: {
          couponName: '新用户专享券',
          couponDesc: '满200减20',
          discountAmount: 20.00
        }
      };
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    uni.showToast({
      title: '获取订单详情失败',
      icon: 'none'
    });
    
    // 使用模拟数据作为备用
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const { id, orderNo } = currentPage.options as any;
    
    orderDetail.value = {
      id: id,
      orderNo: orderNo || 'ORD202501130001',
      status: 1,
      totalAmount: 299.00,
      payAmount: 279.00,
      discountAmount: 20.00,
      createTime: '2025-01-13 10:30:00',
      payTime: '2025-01-13 10:35:00',
      payType: 1,
      orderDetail: [
        {
          id: 1,
          productName: 'iPhone 15 Pro',
          productImage: '/static/images/iphone15.jpg',
          price: 299.00,
          quantity: 1
        }
      ],
      orderCoupon: {
        couponName: '新用户专享券',
        couponDesc: '满200减20',
        discountAmount: 20.00
      }
    };
  }
};

// 处理支付
const handlePay = () => {
  uni.showModal({
    title: "提示",
    content: "确认支付该订单？",
    success: (res) => {
      if (res.confirm) {
        uni.navigateTo({
          url: `/pages/orders/create?orderNo=${orderDetail.value.orderNo}`
        });
      }
    },
  });
};

// 确认收货
const handleConfirmReceive = () => {
  uni.showModal({
    title: "提示",
    content: "确认已收到商品？",
    success: (res) => {
      if (res.confirm) {
        // TODO: 调用确认收货接口
        uni.showToast({
          title: "确认收货成功",
          icon: "success",
        });
        getOrderDetailData(); // 刷新订单详情
      }
    },
  });
};

// 删除订单
const handleDelete = () => {
  uni.showModal({
    title: "提示",
    content: "确认删除该订单？",
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await deleteOrder([orderDetail.value.id]);
          if (response.code === 200) {
            uni.showToast({
              title: "删除成功",
              icon: "success",
            });
            uni.navigateBack();
          } else {
            uni.showToast({
              title: response.msg || "删除失败",
              icon: "none",
            });
          }
        } catch (error) {
          console.error('删除订单失败:', error);
          uni.showToast({
            title: "删除失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 取消订单
const handleCancel = () => {
  uni.showModal({
    title: "提示",
    content: "确认取消该订单？",
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await orderCancel(orderDetail.value.orderNo);
          if (response.code === 200) {
            uni.showToast({
              title: "取消成功",
              icon: "success",
            });
            getOrderDetailData(); // 刷新订单详情
          } else {
            uni.showToast({
              title: response.msg || "取消失败",
              icon: "none",
            });
          }
        } catch (error) {
          console.error('取消订单失败:', error);
          uni.showToast({
            title: "取消失败",
            icon: "none",
          });
        }
      }
    },
  });
};

onMounted(() => {
  getOrderDetailData();
});
</script>

<style scoped>
.order-detail {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.status-section {
  margin-bottom: 20rpx;
}

.status-card {
  background-color: #ffffff;
  padding: 30rpx;
  border-radius: 12rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-title {
  font-size: 28rpx;
  color: #333;
}

.status-text {
  font-size: 32rpx;
  font-weight: bold;
}

.status-0 {
  color: #ff6b00;
}

.status-1 {
  color: #ff6b00;
}

.status-2 {
  color: #07c160;
}

.status-3 {
  color: #ff4d4f;
}

.status-4 {
  color: #999999;
}

.status-5 {
  color: #07c160;
}

.info-section {
  margin-bottom: 20rpx;
}

.info-card {
  background-color: #ffffff;
  padding: 30rpx;
  border-radius: 12rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 28rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  color: #333;
}

.products-section,
.coupon-section,
.price-section {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.products-card,
.coupon-card,
.price-card {
  background-color: #ffffff;
  padding: 30rpx;
  border-radius: 12rpx;
}

.product-item {
  display: flex;
  margin-bottom: 30rpx;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.product-price {
  font-size: 32rpx;
  color: #ff6b35;
  font-weight: bold;
}

.product-quantity {
  font-size: 24rpx;
  color: #999;
}

.coupon-info {
  flex: 1;
}

.coupon-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.coupon-desc {
  font-size: 24rpx;
  color: #666;
}

.discount-amount {
  font-size: 32rpx;
  color: #ff6b35;
  font-weight: bold;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.price-item:last-child {
  margin-bottom: 0;
}

.price-item.total {
  border-top: 1rpx solid #eee;
  padding-top: 20rpx;
  margin-top: 20rpx;
}

.price-item.total .label,
.price-item.total .value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.discount {
  color: #ff6b35;
}

.actions-section {
  padding: 30rpx 0;
  display: flex;
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.action-btn.primary {
  background-color: #007aff;
  color: #ffffff;
}

.action-btn.secondary {
  background-color: #f0f0f0;
  color: #666;
}
</style> 